var intTime = null;
var ytplayer = null;
var qList = new Array();
var cntDown = 15;
var currQ = new Object();
var currIndex = 0;
var timeout = null;
var startIndex = 1;
var maxResult = 10;
var qListLength = 0; //length of the question list

var UserInfo = new Object();
UserInfo.level = 1;
UserInfo.name = "";
UserInfo.uid = 0;
UserInfo.score = 0;
UserInfo.hits = 0;
UserInfo.miss = 0;
UserInfo.currQ = 0;

//jquery stuff
$(function() {
  //init
  $(".debug-area").hide();
  $("#next").button();
  $("#skip").button();
  $("#choice").button();
  $("#invite").button();
  $("#create").button();
  $("#next").bind('click', startQ);
  $("#invite").bind('click', function() {
    $('#player_ol').toggle('slide');
  });
  $("#create").bind('click', function() {
    $('#create-quiz').dialog('open');
  });
  $("#choice").hide();
  $("#skip").hide();
  $("#share-button").hide();
  //getQList();
  updateStatus();
  $("#create-quiz").dialog({ 
                            disabled: true, 
                            autoOpen: false, 
                            modal: true,
                            height: 400, width: 400, 
                            resizable: false, draggable: false,
                            buttons: { "Ok": function() { $(this).dialog("close"); } }
                        });
})

function updateStatus() 
{
  UserInfo.level = Math.floor((UserInfo.score+1000)/1000);
  var tot = UserInfo.miss+UserInfo.hits;
  var pct = ((UserInfo.hits)/tot)*100;

  if(isNaN(pct)) {
    pct = 0;
  }

  if(UserInfo.uid != 0) {
    $("#status").html("Hello,<br>" + UserInfo.name);
  }
  else {
    $("#status").html("Please login using your facebook account to keep track of your scores");
    $("#login-button").show();
  }
  $("#score").html(UserInfo.score);
  $("#level").html(UserInfo.level);
  $("#win_pct").html(pct.toFixed(1));
}

//Youtube stuff
var params = { allowScriptAccess: "always", rel: "0", wmode: "opaque" , autoplay: "1"};
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&version=3", 
                   "ytapiplayer", "100%", "240", "8", null, null, params, atts);

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onYTStateChange");
}

function onYTStateChange(newstate) {
  switch(newstate) {
    case -1:
      $("#debug1").html("unstarted\n");
      break;
    case 0:
      $("#debug1").html("ended");
      resetQ("Hit Play for the next Question");
      break;
    case 1:
      $("#debug1").html("playing\n");
      if(!timeout) {
        $("#debug").append("onYTStateChange: will stop after " +  currQ.playtime + "\n");
        timeout = setTimeout("stopQ()", currQ.playtime*1000); 
      }
      break;
    case 2:
      $("#debug1").html("paused");
      break;
    case 3:
      $("#debug1").html("buffering\n");
      break;
    case 4:
      $("#debug1").html("unknown 4");
      break;
    case 5:
      $("#debug1").html("cued");
      break;
    default:
      break;
  }
}

//fetch the most popular feed from YT and callback updateQList
function getYTList() {

  var feed = 'most_popular';

  var h = document.getElementsByTagName('head').item(0);
  var s = document.createElement("script");
  s.type = "text/javascript";
  s.src="http://gdata.youtube.com/feeds/api/standardfeeds/" + feed + "?time=this_week&alt=json-in-script&callback=updateQList&max-results=" + maxResult + "&start-index=" + startIndex;
  h.appendChild(s);
  $("#debug").append("getYTList: url " + s.src + " \n");
  startIndex += maxResult;
}

//date,id,key,title,author,url,rating,hits,playtime,starttime,album,artist,category,question,choices,answer,points
//callback from getYTList
function updateQList(data) {
  var feed = data.feed;
  var entries = feed.entry || [];
  for (var i = 0; i < entries.length; i++) {
    var q = Object();
    var entry = entries[i];

    q.index = i+1;
    q.date = entry.updated.$t;
    var id = entry.id.$t;
    var j = id.lastIndexOf("/");
    q.vid = id.slice(++j);
    q.author = entry.author[0].name.$t;
    q.title = entry.title.$t;
    q.url = "http://www.youtube.com/v/" + q.vid;
    q.rating = entry.gd$rating.average;
    q.hits = entry.yt$statistics.viewCount;
    q.favorite = entry.yt$statistics.favoriteCount;
    q.starttime = 0;
    q.playtime = 10;
    q.duration = entry.media$group.yt$duration.seconds;
    q.category = entry.category[1].label;
    var obj = getRandomQ(q);
    q.question = obj.question;
    q.answer = obj.answer;
    q.choices = obj.choices.join(',');
    q.points = 100;
    qList.push(q);
  }

  qListLength = qList.length;

  $("#debug").append("getYTList: len " + qList.length + " \n");

  //$("#next").button("option", "label", "Play");
  $("#next").unbind();
  $("#next").bind('click', startQ);
  $("#next").show();
}


function getRandomQ(q) {
  var obj = new Object();
  var str = "";
  var choices = new Array();
  var randPos = Math.floor(Math.random()*5);
  //var type = ['rating', 'title', 'author', 'hits'];
  var type = ['favorite', 'rating', 'hits'];
  var randType = Math.floor(Math.random()*type.length);

  switch(type[randType]) {
    case 'rating':
      str = "Guess the average rating for this video on YouTube ?";
      for(var i=0; i<5; i++) {
        var randChoice = Math.random()*10;
        if(i === randPos) {
          choices[randPos] = q.rating.toFixed(5);
        }
        else {
          choices[i] = randChoice.toFixed(5);
        }
      }
      break;

    case 'favorite':
      str = "What is the favorite count for this video on YouTube ?";
      var len = q.favorite.length;
      var factor = 1;
      for(var i=0; i<len; i++) {
        factor = factor * 10;
      }
      for(var i=0; i<5; i++) {
        var randChoice = Math.floor(Math.random()*factor);
        if(i === randPos) {
          choices[randPos] = q.favorite;
        }
        else {
          choices[i] = randChoice;
        }
      }
      break;

    case 'hits':
      str = "How many time has this video been viewed on YouTube ?";
      var len = q.hits.length;
      var factor = 1;
      for(var i=0; i<len; i++) {
        factor = factor * 10;
      }
      for(var i=0; i<5; i++) {
        var randChoice = Math.floor(Math.random()*factor);
        if(i === randPos) {
          choices[randPos] = q.hits;
        }
        else {
          choices[i] = randChoice;
        }
      }
      break;

    case 'author':
      str = "Who is the author of this video ?";
      choices[randPos] = q.author;
      break;

    case 'title':
      str = "Guess the title of this video ?";
      for(var i=0; i<5; i++) {
        if(i === randPos) {
          choices[randPos] = q.title;
        }
        else {
          choices[i] = '';
        }
      }
      break;

    default:
      break;
  }

  obj.question = str;
  obj.choices = choices;
  obj.answer = randPos;
  return obj;
}

//get list of questions from our server
//date,id,key,title,author,url,rating,hits,playtime,starttime,album,artist,category,question,choices,answer,points
function getQList() {
  var str = "";
  $.ajax({
    type: "GET",
    url: "/get?start=" + startIndex + "&max=" + maxResult,
    dataType: "json",
    success: function(msg) {
      qList = msg;
      qListLength = qList.length;
      if (qListLength === 0) {
        resetQ("Game Over");
        $("#next").unbind();
        $("#next").hide();
        str += 'Thank you for using Kuch Bhi Kya !.<br>';
        str += 'We are constantly adding more questions. Please check again for more trivia.<br><br>';
        str += 'If you would like to try the quiz again, click below<br>';
        str += "<br><button id='reset-game'>Reset Quiz</button>";
        str += '<script type="text\/javascript">\$("#reset-game").button(); $("#reset-game").click(resetQuiz);<\/script>';
        $("#choices").html(str);
        $("#choices").show();
        postUserInfo();
      }
      else { 
        if (startIndex !== 1) {
          resetQ("Hit Play for the next question");
          $("#next").button("option", "label", "Play");
        }
        startIndex += maxResult;
        $("#skip").hide();
        $("#next").unbind();
        $("#next").bind('click', startQ);
        $("#next").show();
      }
    },
    error: function(msg) {
     alert( "error " + msg );
    }
  });
}

//go back to the first question. User will have to take all the questions again
function resetQuiz() {
  resetQ("Hit Play for the next question");
  UserInfo.currQ = 1;
  startIndex = UserInfo.currQ;
  getQList();
}

//set the screen for steady state, no playing, no clicking except next
//msg can be an object (undefined) or string, so set it appropriately to ""
//if its undefined. Otherwise you will see the Hit next Q message unnecessarily
function resetQ(msg) {
  $("#debug").append("resetQ: \n");

  //stop video if running
  if(ytplayer && currQ.type === "VideoClip") {
    ytplayer.stopVideo();
  }

  //hide question and choice boxes
  $("#question").hide();
  $("#choices").hide();

  //unbind the submit button
  $("#choice").unbind();
  $("#choice").hide();

  //stop the countdown timer
  stopCountDown();

  $("#debug").append("resetQ: " + typeof msg + " \n");

  if(!msg) {
    msg = "";
  }

  if(typeof msg != 'string') {
    msg = "Hit Play for the next Question";
  }

  $("#player_ol").html("<h3 class='countdown'>" + msg + "</h3>");
  $("#player_ol").show();

  //$("#next").button("option", "label", "Play");
  $("#skip").hide();
  $("#next").unbind();
  $("#next").bind('click', startQ);
  $("#next").show();
}

function showPlayer(type)
{
  if(type === "AudioClip") {
    $("#qplayer").hide();
    $("#aplayer").show();
    //$("#vplayer").hide();
  }
  else if(type === "VideoClip") {
    $("#qplayer").hide();
    $("#aplayer").hide();
    //$("#vplayer").show();
  }
  else if(type === "Question") {
    $("#qplayer").show();
    $("#aplayer").hide();
    //$("#vplayer").hide();
  }
  $("#player_ol").hide('slide');
}

function skipQ() {
  UserInfo.miss++;
  updateStatus();
  resetQ("Hit Play for next Question");
  $("#question").html("&nbsp;");
  $("#question").show();
};

function startQ() 
{
  if(qList.length ===  0) {
    $("#debug").append("You are done or get more\n");
    resetQ("Get Next " + maxResult + " Questions");
    $("#next").button("option", "label", "Get More");
    $("#next").unbind();
    $("#next").bind('click', getQList);
    //update the last answered question index so next 
    //getQList will get a different set of questions
    currIndex = 0;
    postUserInfo();
    return 0;
  }
  else {
    resetQ();
    $("#next").unbind();
    $("#next").hide();
    $("#skip").bind('click', skipQ);
    $("#skip").show();
    currQ = qList.shift();
    currIndex++;
    UserInfo.currQ++;
  }


  //hide the player overlay and show the appropriate layer 
  //based on the type of question
  showPlayer(currQ.type);

  if(currQ.type === "VideoClip") {
    //start the video
    var url = "http://www.youtube.com/v/" + currQ.vid;

    //XXX sometimes the YT player doesnt seem to like start time 0, although this
    //is not confirmed
    if(currQ.starttime === 0) {
      currQ.starttime++;
    }
    $("#debug").append("startQ: " + url + " " + currQ.starttime + " \n");
    ytplayer.loadVideoByUrl(url, currQ.starttime);

    //start the timer
    //since buffering can take a long time, we want to start
    //the timer when the player get to playing state. see above
  }

  else if(currQ.type === "Question") {
    $("#qplayer").html('<h3 class="countdown countdown_sm">' + currQ.question + '</h3>');
    if(!timeout) {
      timeout = setTimeout("stopQ()", currQ.playtime*1000); 
    }
  }

  $("#question").html("Question " + currIndex + " of " + qListLength);
  $("#question").show();

}

//set when the video starts playing, typically after playtime
//specified in the question list for the video.
function stopQ() 
{
  $("#debug").append("stopQ: intTime " + intTime + " \n");

  if(currQ.type === "VideoClip") {
    ytplayer.stopVideo();
  }

  //create and show question and choices
  showQuestion();
  fillChoices();
  $("#choices").slideDown('slow');

  //get ready for an answer
  $("#choice").bind('click', checkAnswer);
  $("#choice").show();

  $("#next").unbind();
  $("#next").hide();
  $("#skip").unbind();
  $("#skip").hide();

  //display overlay with countdown and start countdown
  $("#player_ol").html('<h1 class="countdown">' + cntDown + '</h1>');
  if(!intTime) {
    intTime = setInterval("startCountDown()", 1000); 
  }
  $("#player_ol").show('clip', 1000);
}

function startCountDown() 
{
  if (cntDown === 15) {
    $("#debug").append("startCD " + cntDown + "\n");
  }

  $("#player_ol").html('<h1 class="countdown">' + cntDown + '</h1>');
  cntDown--;

  if (cntDown === -1) {
    resetQ("Time Up!");
    showAnswer();
    UserInfo.miss++;
    updateStatus();
  }
}

function stopCountDown() 
{
  $("#debug").append("stopCD " + intTime + " \n");

  if(intTime) {
    clearInterval(intTime);
    intTime = null;
  }
  if(timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  cntDown = 15;
}

function fillChoices() 
{
  var arr = currQ.choices.split(',');
  var str = "";

  for (var i = 0; i < arr.length; i++ ) {
    str += "<input type='radio' name='answers' value='" + i + "'>" + arr[i] + "<br>";
  }
  $("#choices").html(str);
}

function showQuestion() {
  if(currQ.question.length > 75) {
    $("#question").html("<span style='font-size: 12px;'>" + currQ.question + "</span>");
  }
  else {
    $("#question").html(currQ.question);
  }
  $("#question").slideDown('slow');
}

function checkAnswer() 
{
  var msg = "";
  var v = $('input:radio[name=answers]:checked').val();
  v = parseInt(v);
  if (v === currQ.answer) {
      UserInfo.score += parseInt(currQ.points);
      UserInfo.hits++;
      msg = "That's right !<br>Score: " + UserInfo.score;
  }
  else {
      msg = "Kuch Bhi Kya !";
      UserInfo.miss++;
  }
  updateStatus();
  postUserInfo();
  resetQ(msg);
  showAnswer();
}

function showAnswer() 
{
  var str = "";
  var arr = currQ.choices.split(',');
  for (var i = 0; i < arr.length; i++ ) {
    if(i === currQ.answer) {
      str = arr[i];
    }
  }
  if(currQ.type === "VideoClip") {
    str += "<br><br><br><button id='fullvideo'>Watch Full Video</button>";
    str += '<script type="text\/javascript">\$("#fullvideo").button(); $("#fullvideo").click(fullVideo);<\/script>';
  }
  $("#choices").html("Answer: " + str);
  $("#choices").show();
  showQuestion();
}

function fullVideo() 
{
  //hide the player overlay
  $("#player_ol").hide();
  $("#choices").html();

  //start the video
  var url = "http://www.youtube.com/v/" + currQ.vid;
  currQ.playtime = currQ.duration+1;
  ytplayer.loadVideoByUrl(url, 0);
}

function getUserInfo() 
{
  var uid = UserInfo.uid;
  var uname = UserInfo.name;
  $.ajax({
     type: "GET",
     url: "/userinfo?uid=" + uid,
     dataType: "json",
     success: function(msg) {
       $("#debug").append("success getUserinfo: uid=" + msg.uid + " score= " + msg.score + " name= " + msg.name + "<br>");
        UserInfo=msg;
        //if no such user is present, indicated by uid==0, reset the uid to what we got from FB
        if(UserInfo.uid === 0) {
          UserInfo.uid = uid;
          UserInfo.name = uname;
          postUserInfo();
        }
        startIndex = UserInfo.currQ;
        getQList();
        updateStatus();
     },
     error: function(msg) {
       $("#debug").append("error getUserinfo " + msg + "<br>");
     }
   });
}

function postUserInfo() 
{
  $("#debug").append("postUserinfo uid=" + UserInfo.uid + "<br>");

  if(UserInfo.uid === 0) {
    $("#debug").append("No UserInfo available, no need to post anything <br>");
    return 0;
  }

  $.ajax({
     type: "POST",
     url: "/userinfo",
     data: JSON.stringify(UserInfo),
     success: function(msg) {
       $("#debug").append("success postUserinfo " + msg + "<br>");
     },
     error: function(msg) {
       $("#debug").append("error postUserinfo " + msg + "<br>");
     }
   });
}
